package com.danicsoft.daide.gui;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import com.danicsoft.daide.historian.Textbook;

public class GUITextbookFrame extends JFrame {

	private class GUITextbook extends Textbook implements ListModel {
		
		public GUITextbook(int importanceLevel) {
			super(importanceLevel);
			
		}

		private List<ListDataListener> listeners = new LinkedList<ListDataListener>();
		
		private List<String> messages = new ArrayList<String>();
		@Override
		protected void outputMessage(Object actor, String message, int importance) {
			messages.add(actor.toString() + "> " + message);
			for(ListDataListener listener : listeners) {
				listener.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, messages.size() - 1, messages.size() - 1));
			}
			listbox.setSelectedIndex(messages.size() - 1);
			sPane.getVerticalScrollBar().setValue(sPane.getVerticalScrollBar().getMaximum());

		}

		public void addListDataListener(ListDataListener l) {
			listeners.add(l);

		}

		public Object getElementAt(int index) {
			return messages.get(index);
		}

		public int getSize() {
			return messages.size();
		}

		public void removeListDataListener(ListDataListener l) {
			listeners.remove(l);

		}

	}

	private JPanel jContentPane = null;
	private GUITextbook myTextbook;
	private JList listbox;
	private JScrollPane sPane;

	/**
	 * This is the default constructor
	 */
	public GUITextbookFrame(int importanceLevel) {
		super("Yo' mom!");
		initialize(importanceLevel);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize(int importanceLevel) {
		this.setSize(300, 200);
		this.setContentPane(getJContentPane(importanceLevel));
		this.setTitle("JFrame");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane(int importanceLevel) {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			myTextbook = new GUITextbook(importanceLevel);
			listbox = new JList(myTextbook);
			sPane = new JScrollPane(listbox);
			jContentPane.add(sPane);
		}
		return jContentPane;
	}
	
	public Textbook getTextbook() {
		return myTextbook;
	}
	
	public static void main(String [] args) {
		JFrame gFrame = new GUITextbookFrame(0);
		gFrame.setVisible(true);
	}

}
